package com.sen.uaa.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.sen.common.common.bo.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 自定义token携带的附加信息
 * @Author esJiang
 **/
@Component
public class TokenEnhancerConfig implements TokenEnhancer {

    private static final String PEOPLE_ID = "peopleId" ;

    private static final String ENTITY_CODE = "entityCode" ;

    private static final String USER_NAME = "userName" ;

    private static final String SYSTEM_CODE = "systemCode" ;

    private static final String ENTITY_TYPE = "entityType" ;

    private static final String TENANT_CODE = "tenantCode" ;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        User user = (User) oAuth2Authentication.getPrincipal() ;
        additionalInfo.put(TENANT_CODE, Convert.toStr(user.getSysAccount().getTenantCode())) ;
        additionalInfo.put(USER_NAME, Convert.toStr(user.getUsername())) ;
        additionalInfo.put(SYSTEM_CODE,ParamsContextHolder.getParams().get(SYSTEM_CODE)) ;
        additionalInfo.put(ENTITY_TYPE,ParamsContextHolder.getParams().get(ENTITY_TYPE)) ;
        if (ObjectUtil.isNotNull(user.getPeopleInfo())){
            additionalInfo.put(PEOPLE_ID, Convert.toStr(user.getPeopleInfo().getPeopleId())) ;
            additionalInfo.put(ENTITY_CODE, Convert.toStr(user.getPeopleInfo().getEntityCode())) ;
        }
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(additionalInfo);
        if (userAuthentication == null) {
            return oAuth2AccessToken ;
        }
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(additionalInfo);
        return oAuth2AccessToken;
    }
}
